define(["jquery","comm/form/form.attention","comm/form/form.validate"],function($,$attention,$validate){
	var quest = {};
	
	/**
	 * 数据处理(若不需要数据处理，可以不写)
	 */
    quest.formatData = function(obj){
    	for (var i = 0; i < obj.list.length; i++) {
    		if( typeof obj.list[i] == "string" ){
    			var str = obj.list[i];
    			obj.list[i] = {};
    			obj.list[i].key = str;
    			obj.list[i].text = str;
    		}
    	}
    	if( obj.relation && typeof obj.relation == "object" && !$.isArray(obj.relation) ){
    		var obj_relation = obj.relation;
    		obj.relation = [];
    		obj.relation.push(obj_relation);
    	}
    	if( obj.relation && $.isArray(obj.relation) ){
    		for (var i = 0; i < obj.list.length; i++) {
    			for (var j = 0; j < obj.relation.length; j++) {
    				if( obj.list[i].key == obj.relation[j].relationKey ){
    					obj.list[i].relationId = obj.relation[j].relationId;
    					break;
    				}
    			}
    		}
    	}
		return obj;
	}

	/**
	 * tpl模板
	 */
	quest.tpl = function(){
		return 	'<script id="tpl_question_checkboxRelation" type="text/html">'+
				'	<div {{if relationId}}data-relationId="{{relationId}}"{{/if}} class="qaCard qaCard-checkboxRelation form-group form-group-sm col-sm-{{length}} col-md-{{length}} grid-label-{{labelLength}}">'+
				'		<label class="control-label {{align}}">{{label}}</label>'+
				'   	<div class="control-input checkbox {{if status!="default" }}disabled{{/if}}">'+
				'			{{if status=="default"}}'+
				'				{{each list as item i}}'+
				'					<label>'+
				'						<input type="checkbox" class="validatebox" name="{{name}}" rId="{{item.relationId}}" value="{{item.key}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" {{if dataUnit}}data-dataUnit="{{dataUnit}}"{{/if}} data-validate="{{validate}}" data-attention="{{attention}}">'+
				'						{{item.text}}'+
				'					</label>'+
				'				{{/each}}'+
				'			{{else if status=="readonly"}}'+
				'				{{each list as item i}}'+
				'					<label>'+
				'						<input type="checkbox" class="validatebox" name="{{name}}" rId="{{item.relationId}}" value="{{item.key}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" {{if dataUnit}}data-dataUnit="{{dataUnit}}"{{/if}} data-validate="{{validate}}" data-attention="{{attention}}" disabled>'+
				'						{{item.text}}'+
				'					</label>'+
				'				{{/each}}'+
				'			{{else if status=="disabled"}}'+
				'				{{each list as item i}}'+
				'					<label>'+
				'						<input type="checkbox" class="validatebox" name="{{name}}" rId="{{item.relationId}}" value="{{item.key}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" {{if dataUnit}}data-dataUnit="{{dataUnit}}"{{/if}} data-validate="{{validate}}" data-attention="{{attention}}" disabled>'+
				'						{{item.text}}'+
				'					</label>'+
				'				{{/each}}'+
				'			{{/if}}'+
				'		</div>'+
				'	</div>'+
				'</script>';
	}

	/**
	 * 赋值
	 */
	quest.setValue = function($dom,value){
		if( value ){
			if( value.quesValue && value.quesValue.indexOf("[") >= 0 && value.quesValue.indexOf("]") >= 0 ) value.quesValue = JSON.parse(value.quesValue);
			if( value.quesValue && $.isArray(value.quesValue) && value.quesValue.length > 0 ){
				for (var i = 0; i < value.quesValue.length; i++) {
					$dom.each(function(j){
						if( value.quesValue[i] == $(this).val() ){
							$(this).attr("checked","checked");
							$(this).trigger("change");
							return true; // 退出本次循环
						}
					});
				}
			}
		}
	}

	/**
	 * 获取value（保存时，获取每个dom对应的答案）
	 */
	quest.getValue = function($dom,name){
		var domArr = $dom.parents(".qaCard").find("input[type='checkbox'][name='" + name + "']:checked");
		var val = [];
		domArr.each(function(){
			val.push( $(this).val() );
		});
		var value = {};
		value.quesValue = JSON.stringify(val);
		value.quesId = $dom.attr("data-quesId");
		value.deCode = $dom.attr("data-deCode");
		value.innDeCode = $dom.attr("data-innDeCode");
		var dataUnit = $dom.attr("data-dataUnit");
		if( dataUnit ) value.dataUnit = dataUnit;
		return value;
	}

	/**
	 * 事件(若没有事件函数，可以不写)
	 */
	quest.event = function(params,id){
		var dom = $("#" + id + " .qaCard[relationId]"); // 表单里带relationId的dom元素
		// 选中某个复选项，某个复选项对应的才显示
		$("#" + id + " .qaCard-checkboxRelation .checkbox input:checkbox").unbind("change");
		$("#" + id + " .qaCard-checkboxRelation .checkbox input:checkbox").data({"dom":dom});
		$("#" + id + " .qaCard-checkboxRelation .checkbox input:checkbox").bind("change",onCheckboxRelation);
	}

	/**
	 * 提醒
	 */
	quest.attention = function(id){
        $("#" + id + " .qaCard-checkboxRelation .validatebox").bind("blur",onAttention);
        // 初始化
        $("#" + id + " .qaCard-checkboxRelation .validatebox").blur();
	}

	/**
	 * 校验
	 * flag:
	 * 	 true:  (点击保存按钮时使用)
	 * 	 false: 
	 */
	quest.validate = function(id,flag){
        $("#" + id + " .qaCard-checkboxRelation .validatebox").bind("blur",onValidate);
        if( flag ){
        	var result = true;
        	$("#" + id + " .qaCard-checkboxRelation").each(function(i){
        		var dom = $(this).find(".validatebox").eq(0);
        		var params = {
		            "value":getValue(dom),
		            "dom":dom,
		            "flag":flag,
		        };
				var success = $validate.init(params,handleByRuleValidate,handleBytypeValidate);
	            result = result && success;
	            if( !result ) return result;
	    	});
        	return result;
        }
	}

	/******************** event begin ********************/

	var onCheckboxRelation = function(event){
		var dom = $(this).data("dom");
		var This = $(this);
		var rId = This.attr("rId");
		dom.each(function(j){
			if(dom.eq(j).attr("relationId") == rId){
				if( This.is(':checked') ){
					dom.eq(j).show();
				}else{
					dom.eq(j).hide();
				}
			}
		});
	}

	/******************** event end ********************/

	/**
	 * 获取输入的值(validate、attention中需要用到)
	 */
	var getValue = function($dom){
		var domArr = $dom.parents(".qaCard").find("input[type='checkbox']:checked");
		var value = [];
		domArr.each(function(){
			value.push( $(this).val() );
		});
		return value;
	}

	/********************  attention begin  ********************/

	/**
	 * xx情况下触发的事件 (有可能是失去焦点等)
	 */
	var onAttention = function(){
		var params = {
            "value":getValue($(this)),
            "dom":$(this),
        };
		$attention.init(params,handleByRule,handleBytype);
    }

    /**
     * 根据单个规则rule获取单个规则的结果result
     * 该题型已有规则在case里拦截，公用规则从default里返回结果
     * @return Boolean [布尔值]
     */
    var handleByRule = function(obj){
    	var result;
        return result;
    }

    /**
     * 根据提醒类型(type)执行对应的方法
     * 该题型已有提醒类型在case里拦截，公用提醒类型在default里处理
     */
    var handleBytype = function(obj){
    	if( obj.type ){
    		switch(obj.type) {
    			case "tips_icon":    // 图标提醒(拦截重置)
	                tips_icon(obj);
	                break;
	            case "text_warn":    // 文字警告提醒(拦截过滤)
                    break;
	            default:
            		$attention.handleBytype(obj);
	        }
    	}
    }

    /**
     * 图标提示
     */
    var tips_icon = function(obj){
        view_tips_icon(obj)
    }

    /**
     * 图标提示
     */
    var view_tips_icon = function(obj){
        if( obj.result ){
            var $dom = obj.dom.parents(".control-input");
            if( !obj.view ) obj.view = {};
            if( !obj.view.icon ) obj.view.icon = "fa fa-question-circle";
            if( !obj.view.color ) obj.view.color = "#00E0BF";
            if( !obj.view.msg ) obj.view.msg = "提示";
            var h = '<i class="control-icon control-icon-2 '+ obj.view.icon +'" style="color:'+ obj.view.color +'" data-toggle="tooltip" data-placement="left" title="'+ obj.view.msg +'"></i>';
            if( $dom.find("i.control-icon").length == 0 ) $dom.append(h);
            $(function(){$('[data-toggle="tooltip"]').tooltip()});
        }
    }

    /********************  attention end  ********************/

    /********************  validate begin  ********************/

    /**
	 * xx情况下触发的事件 (有可能是失去焦点等)
	 */
	var onValidate = function(){
		var params = {
            "value":getValue($(this)),
            "dom":$(this),
        };
		$validate.init(params,handleByRuleValidate,handleBytypeValidate);
	}

	/**
     * 根据单个规则rule获取单个规则的结果result
     * 该题型已有规则在case里拦截，公用规则从default里返回结果
     * @return Boolean [布尔值]
     */
    var handleByRuleValidate = function(obj){
    	var result = true;
    	switch(obj.type) {
            case "noNull":  // 非空
                result = noNull(obj);
                break;
        }
        return result;
    }

    /**
     * 根据提醒类型(type)执行对应的方法
     * 该题型已有提醒类型在case里拦截，公用提醒类型在default里处理
     */
    var handleBytypeValidate = function(obj){
    	if( obj.type ){
    		switch(obj.type) {
    			case "border_warn":    // 边框警告校验(拦截过滤)
                    break;
	            default:
            		$validate.handleBytype(obj);
	        }
    	}
    }

    /**
     * 校验规则 非空
     */
    var noNull = function(params){
        var success = params.value.length > 0 ? true : false;
        return success;
    }

	/********************  validate begin  ********************/

	return quest;
});